package com.ironman.mes.plugin.common.config;

import com.ironman.mes.plugin.common.properties.MqttClientProperties;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.codec.MqttTopicSubscription;
import net.dreamlu.iot.mqtt.core.client.IMqttClientConnectListener;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import org.noear.dami.Dami;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Configuration;
import org.tio.core.ChannelContext;

import java.util.stream.Collectors;

@Slf4j
@Configuration
public class MqttClientConfig {

    @Bean
    @Condition(onProperty = "${mqtt.client.enabled} = true")
    public MqttClient mqttClient(MqttClientProperties mqttClientProperties) {
        return MqttClient.create()
                .clientId(mqttClientProperties.getClientId())
                .ip(mqttClientProperties.getIp())
                .port(mqttClientProperties.getPort())
                .username(mqttClientProperties.getUserName())
                .password(mqttClientProperties.getPassword())
                .retryCount(mqttClientProperties.getRetryCount())
                .keepAliveSecs(mqttClientProperties.getKeepAliveSecs())
                .connectListener(new IMqttClientConnectListener() {
                    @Override
                    public void onConnected(ChannelContext context, boolean isReconnect) {
                        log.info("链接服务器成功...");
                    }

                    @Override
                    public void onDisconnect(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
                        log.info("与链接服务器断开连接...");
                    }
                })
                .globalSubscribe(mqttClientProperties.getTopics().stream().map(n -> new MqttTopicSubscription(n.getTopic(), MqttQoS.valueOf(n.getQos()))).collect(Collectors.toList()))
                .globalMessageListener((context, topic, message, payload) -> Dami.bus().send(topic, new String(payload)))
                .connect();
    }
}
